//
//  CacheDaoForComment.m
//  GolfFriend
//
//  Created by Vescky on 14-3-1.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "CacheDaoForComment.h"
#import "DateUtility.h"

#define TB_CACHE_COMMENTS @"tb_cache_comments"

@implementation CacheDaoForComment
static CacheDaoForComment *defaultCommentCacher;

+ (id)shareCacheDaoForComment {
    if (!defaultCommentCacher) {
        defaultCommentCacher = [[CacheDaoForComment alloc] init];
        DB *dbase = [[DB alloc] init];
        FMDatabase *database = [dbase getDatabase];
        [database executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(id integer primary key,type text,recordId text,userId text,content text)",TB_CACHE_COMMENTS]];
        [database close];
    }
    return defaultCommentCacher;
}

// -- userId
// -- type:news,circle,stadium
// -- recordId
// -- content
- (bool)saveCommentInfo:(NSDictionary*)dict {
    if (!dict || [dict count] < 4) {
        return NO;
    }
    if ([self ifRecordExist:dict]) {
        return NO;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
    if (!params || [params count] < 1) {
        return NO;
    }
    
    [self insert:params inTable:TB_CACHE_COMMENTS];
    
    return YES;
}

- (bool)saveComments:(NSMutableArray*)cArr {
    if (!cArr || [cArr count] < 1) {
        return NO;
    }
    
    for (int i = 0; i < [cArr count]; i++) {
        [self saveCommentInfo:[cArr objectAtIndex:i]];
    }
    
    return YES;
}

// -- userId
// -- type:news,circle,stadium
// -- recordId
- (bool)getComments:(NSDictionary*)dict limitRange:(NSRange)lRange {
    NSMutableArray *allData = [self queryByConfition:[NSString stringWithFormat:@"select * from %@ where userId = '%@' and type = '%@'",TB_CACHE_COMMENTS,[dict objectForKey:@"userId"],[dict objectForKey:@"type"]]];
    NSMutableArray *arrLimitted = [[NSMutableArray alloc] init];
    if ([allData count] > lRange.length) {
        arrLimitted = [[NSMutableArray alloc] initWithArray:[allData subarrayWithRange:lRange]];
    }
    else {
        arrLimitted = [[NSMutableArray alloc] initWithArray:allData];
    }
    
    //按时间，从早到晚排序
    NSArray *sortedArr = [arrLimitted sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate *date1 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", [obj1 objectForKey:@"time"]);
        NSDate *date2 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", [obj2 objectForKey:@"time"]);
        if ([date2 isEqualToDate:[date1 laterDate:date2]]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        else {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    
    return [[NSMutableArray alloc] initWithArray:sortedArr];
}

- (bool)deleteCommentsByUserId:(NSString*)userId {
    DB *dbase = [[DB alloc] init];
    FMDatabase *database = [dbase getDatabase];
    return [database executeUpdate:[NSString stringWithFormat:@"delete * from %@ where userId = '%@'",TB_CACHE_COMMENTS,userId]];
}

- (bool)cleanAllComments {
    DB *dbase = [[DB alloc] init];
    FMDatabase *database = [dbase getDatabase];
    bool flag = [database executeUpdate:[NSString stringWithFormat:@"delete from %@",TB_CACHE_COMMENTS]];
    if (flag) {
        flag = [database executeUpdate:[NSString stringWithFormat:@"update sqlite_sequence set seq=0 where name = '%@'",TB_CACHE_COMMENTS]];
    }
    [database close];
    return flag;
}

#pragma - Private
- (bool)ifRecordExist:(NSDictionary*)dict {
    if (!dict || [dict count] < 1) {
        return NO;
    }
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where userId = '%@' and recordId = '%@'",TB_CACHE_COMMENTS,[dict objectForKey:@"userId"],[dict objectForKey:@"recordId"]];
    NSMutableArray *arr = [self queryByConfition:qConfition];
    if (arr && [arr count] > 0) {
        return YES;
    }
    return NO;
}

@end
